package com.fescoservice.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.fescoservice.config.PropertiesConfig;
import com.fescoservice.exception.FSException;
import com.fescoservice.model.Company;
import com.fescoservice.model.Customer;
import com.fescoservice.util.Constants;
import com.fescoservice.util.MiscUtil;

/**
 * A data access object (DAO) providing persistence and search support for
 * Customer entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.fescoservice.dao.Customer
 * @author MyEclipse Persistence Tools
 */

public class CustomerDAO extends HibernateDaoSupport {
	private static final Logger log =  LogManager.getLogger(CustomerDAO.class);
	// property constants
	public static final String CUST_NAME_CN = "custNameCn";
	public static final String CUST_NAME_EN = "custNameEn";
	public static final String PASS_ID = "passId";
	public static final String PASS_VALID_DATE = "passValidDate";
	public static final String COMPANY_ID = "companyId";
	public static final String COMPANY_NAME = "companyName";
	public static final String COMPANY_ADDR = "companyAddr";
	public static final String BIRTH_DATE = "birthDate";
	public static final String PHONE = "phone";
	public static final String CUST_ADDR = "custAddr";

	protected void initDao() {
		// do nothing
	}
	
	
	
	/**
	 * 查询 count(1)
	 * @param sql
	 * @return
	 * @throws FSException
	 */
	public Long countCustomers(final String sql,final String serchOptionSel,final String serchOptionValue) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);							
						   log.debug("~~~~~~~~~L81~~~~~~~~~~~~~~~~~`````"); 
						   System.out.println("L72 countCustomers q.toString():"+q.toString());
						  return q.addScalar( "cnt" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count customers failed", re);
			throw new FSException("FS_ERROR_COUNT_CUSTOMERS",re.getMessage());
		}
	}
	
	/**
	 * 查询 companyId
	 * @param sql
	 * @return
	 * @throws FSException
	 */
	public Long getCustomerId(final String sql) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);
						 //  q.setDate("enddate" , endDate); //endDate java.sql.Date   
						   log.debug("~~~~~~~~~L89~~~~~~~~~~~~~~~~~`````"); 
						  return q.addScalar( "custId" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count companies failed", re);
			throw new FSException("FS_ERROR_COUNTCATGORY",re.getMessage());
		}
	}
	
	
	
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List findCustomerByProperty(final String hql,final String serchOptionSel,final String serchOptionValue,final int companyId,final int first)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   	if(companyId > 0){
								q.setInteger("companyId" , companyId); 	
							}
							if(!MiscUtil.isNullOrEmpty(serchOptionSel)&&!MiscUtil.isNullOrEmpty(serchOptionValue)){
								if(Constants.CUSTOMER_PASS_SEL.equals(serchOptionSel)){
									q.setString("passId" , serchOptionValue); 	
								}
								if(Constants.CUSTOMER_NAME_EN_SEL.equals(serchOptionSel)){
									q.setString("custFirstnameEn" , serchOptionValue); 
									
								}
								if(Constants.CUSTOMER_COMPANY_SEL.equals(serchOptionSel)){
									q.setString("companyName" , serchOptionValue); 
								}
							}
							q.setFirstResult(first);
							q.setMaxResults(PropertiesConfig.getInstance().getInt("ListSize.Customer"));
						   log.debug("~~~~~~~~~findCompanyByName L176~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("findCompanyByName failed", re);
			throw re;
		}
	}
	
	
	
	
	/**
	 * 查询 count(1)
	 * @param sql
	 * @return
	 * @throws FSException
	 */
	public Long countApplications(final String sql,final String userId,final String userRole,final String userDept,final String custId) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);							
						   log.debug("~~~~~~~~~L81~~~~~~~~~~~~~~~~~`````");
						   System.out.println("L167  countApplications:"+q.getQueryString());
						  return q.addScalar( "cnt" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count customers failed", re);
			throw new FSException("FS_ERROR_COUNT_CUSTOMERS",re.getMessage());
		}
	}
	
	
		/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List getApplications(final String hql,final String userId,final String userRole,final String userDept,final String custId)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   
							if(Constants.OPERATOR_ROLE_CEO.equals(userRole)){
								// do nothing
							}else if(Constants.OPERATOR_ROLE_MANAGER.equals(userRole)){			
								q.setString("deptId" , userDept); 			
							}else if(Constants.OPERATOR_ROLE_BUSSINESS_MAN.equals(userRole)){
								q.setString("creatorId" , userId); 	
							}
							
							if(!MiscUtil.isNullOrEmpty(custId)){
								q.setInteger("custId" , Integer.valueOf(custId)); 	
							}
							System.out.println("L206 getApplications:"+q.getQueryString());
						    
						   log.debug("~~~~~~~~~findCompanyByName L176~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("findCompanyByName failed", re);
			throw re;
		}
	}
	
	
	
	
	
	
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List viewApplications(final String hql,final String applyId,final String custId)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
							
							if(!MiscUtil.isNullOrEmpty(custId)){
								q.setInteger("custId" , Integer.valueOf(custId)); 	
							}
							
							if(!MiscUtil.isNullOrEmpty(applyId)){
								q.setInteger("applyId" , Integer.valueOf(applyId)); 	
							}
							
							System.out.println("L248 viewApplications:"+q.getQueryString());
						    
						   log.debug("~~~~~~~~~findCompanyByName L176~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("findCompanyByName failed", re);
			throw re;
		}
	}
	
	
	
	
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws FSException
	 */
	public List custLogin(final String hql,final String userId,final String userPass)  throws FSException{
		try {
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   q.setString("userId" , userId); 	
						   q.setString("userPass" , userPass); 	
						   log.debug("~~~~~~~~~custLogin L230~~~~~~~~~~~~~~~~~`````"); 
						   System.out.println("custLogin L231:"+q.getQueryString());
						   System.out.println("custLogin L232:"+q.toString());
						  return q.list();
					   }
					 } );
			return rs;
		} catch (RuntimeException re) {
			log.error("custLogin failed", re);
			throw re;
		}
	}
	
	
	
	
	/**
	 * 根据Id查询Company
	 * @param hql
	 * @param compId
	 * @return
	 * @throws Exception 
	 * @throws FSException
	 */
	public List queryCustLogin(final String hql,final String userId) throws FSException{

		try{
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   q.setString("userId" , userId);   
						   System.out.println("~~~~~~~~~queryCustLogin L146~~~~~~~~~~~~~~~~~`````"); 
						  return q.list();
					   }
					 } );
			return rs;
		}catch (RuntimeException re) {
			log.error("queryCustLogin failed", re);
			throw re;
		}

	}
	
	
	
	
	
	
	public List formatUserId(final String hql,final String userId) throws Exception{

		try{
			List rs = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(hql);
						   q.setString("userId" , userId); 	
						   log.debug("~~~~~~~~~custLogin L259~~~~~~~~~~~~~~~~~`````"); 
						   System.out.println("custLogin L260: "+q.getQueryString());
						   System.out.println("custLogin L261: "+q.toString());
						  return q.list();
					   }
					 } );
			return rs;
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}

	}
	
	
	
	
	
	

	public void save(Customer transientInstance) {
		log.debug("saving Customer instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	

	public void delete(Customer persistentInstance) {
		log.debug("deleting Customer instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Customer findById(Integer id) {
		log.debug("getting Customer instance with id: " + id);
		try {
			Customer instance = (Customer) getHibernateTemplate().get(
					"com.fescoservice.model.Customer", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Customer instance) {
		log.debug("finding Customer instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Customer instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Customer as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByCustNameCn(Object custNameCn) {
		return findByProperty(CUST_NAME_CN, custNameCn);
	}

	public List findByCustNameEn(Object custNameEn) {
		return findByProperty(CUST_NAME_EN, custNameEn);
	}

	public List findByPassId(Object passId) {
		return findByProperty(PASS_ID, passId);
	}

	public List findByPassValidDate(Object passValidDate) {
		return findByProperty(PASS_VALID_DATE, passValidDate);
	}

	public List findByCompanyId(Integer companyId) {
		return findByProperty(COMPANY_ID, companyId);
	}

	public List findByCompanyName(Object companyName) {
		return findByProperty(COMPANY_NAME, companyName);
	}

	public List findByCompanyAddr(Object companyAddr) {
		return findByProperty(COMPANY_ADDR, companyAddr);
	}

	public List findByBirthDate(Object birthDate) {
		return findByProperty(BIRTH_DATE, birthDate);
	}

	public List findByPhone(Object phone) {
		return findByProperty(PHONE, phone);
	}

	public List findByCustAddr(Object custAddr) {
		return findByProperty(CUST_ADDR, custAddr);
	}

	public List findAll() {
		log.debug("finding all Customer instances");
		try {
			String queryString = "from Customer";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Customer merge(Customer detachedInstance) {
		log.debug("merging Customer instance");
		try {
			Customer result = (Customer) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Customer instance) {
		log.debug("attaching dirty Customer instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Customer instance) {
		log.debug("attaching clean Customer instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CustomerDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CustomerDAO) ctx.getBean("CustomerDAO");
	}
	
	
	public void update(final String hql, final Customer customer)  throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
					Query q = session.createQuery(hql);
						q.setString("custFirstnameEn" , customer.getCustFirstnameEn()); 	
						q.setString("custLastnameEn" , customer.getCustLastnameEn()); 
						q.setString("passId" , customer.getPassId()); 
						q.setString("passValidDate" , customer.getPassValidDate()); 
						q.setString("custNameCn" , customer.getCustNameCn()); 
						q.setString("birthDate" , customer.getBirthDate()); 	
						q.setString("phone" , customer.getPhone()); 
						q.setString("companyName" , customer.getCompanyName()); 						
						if(!MiscUtil.isNullOrEmpty(customer.getCompanyId())){
							q.setInteger("companyId" , customer.getCompanyId()); 
						}
						q.setString("companyAddr" , customer.getCompanyAddr()); 
						q.setString("custAddr" , customer.getCustAddr()); 
						q.setInteger("custId" , customer.getCustId()); 
						System.out.println("L486:-------------"+q.getQueryString());
					q.executeUpdate();
				return null;
			}
		});

	}
	
	
	public void delete(final String hql, final Customer customer)  throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
						Query q = session.createQuery(hql);
						q.setInteger("custId" , customer.getCustId()); 
						q.executeUpdate();
				return null;
			}
		});

	}
	
	
}